package com.fitness.front.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fitness.front.convertor.UserConvertor;
import com.fitness.front.mapper.*;
import com.fitness.front.modal.coach.entity.Coach;
import com.fitness.front.modal.course.entity.CoachCourse;
import com.fitness.front.modal.course.entity.MemberCourse;
import com.fitness.front.modal.course.entity.MemberCoursePlan;
import com.fitness.front.modal.member.entity.Member;
import com.fitness.front.modal.response.ServerResponseEntity;
import com.fitness.front.modal.user.dto.UserDto;
import com.fitness.front.modal.user.entity.Role;
import com.fitness.front.modal.user.entity.RoleUser;
import com.fitness.front.modal.user.entity.User;
import com.fitness.front.modal.user.param.UserPageQueryParams;
import com.fitness.front.modal.user.vo.UserVO;
import com.fitness.front.service.IUserService;
import com.fitness.front.utils.EncryptUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    private final UserConvertor userConvertor;

    private final static String DEFAULT_PASSWORD = "123456";

    private final RoleUserMapper roleUserMapper;
    private final RoleMapper roleMapper;

    private final MemberCourseMapper memberCourseMapper;
    private final MemberCoursePlanMapper memberCoursePlanMapper;

    private final CoachCourseMapper coachCourseMapper;
    private final MemberMapper memberMapper;
    private final CoachMapper coachMapper;

    @Override
    public void logout() {
        StpUtil.logout();
    }

    @Override
    public Page<UserVO> getUserPage(UserPageQueryParams queryParams) {
        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<User> page = new Page<>(pageNum, pageSize);

        // 查询数据
        Page<User> userBoPage = this.baseMapper.getUserPage(page, queryParams);

        return userConvertor.entity2Vo(userBoPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUser(UserDto userDto) {
        User user = userConvertor.dto2Entity(userDto);
        int start = RandomUtil.randomInt(0,EncryptUtil.PASSWORD_SALT.length() - 1, true, false);
        String salt = EncryptUtil.PASSWORD_SALT.substring(start,
                RandomUtil.randomInt(start,EncryptUtil.PASSWORD_SALT.length(),true, false));
        user.setSalt(salt);
        user.setPassword(EncryptUtil.encryptPassword(DEFAULT_PASSWORD,salt));
        boolean result = this.save(user);
        RoleUser roleUser = new RoleUser();
        roleUser.setUserId(user.getId());
        roleUser.setRoleId(userDto.getRoleId());
        roleUserMapper.insert(roleUser);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(UserDto userDto) {
        User user = userConvertor.dto2Entity(userDto);
        boolean result = this.baseMapper.updateById(user) > 0;
        if(!result){
            return false;
        }
        return roleUserMapper.updateRoleUserByUid(userDto.getRoleId(),user.getId()) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Boolean> removeByUid(Long uid) {
        Role role = roleMapper.getRoleByUid(uid);
        String roleName = role.getName();
        //如果是学员，则需要看该学员是否还有未完成的课程，如果有，就不能删除该用户
        if(roleName.equals("trainee")){
            QueryWrapper<MemberCourse> memberCourseQueryWrapper = new QueryWrapper<>();
            memberCourseQueryWrapper.eq("user_id", uid);
            if(!memberCourseMapper.selectObjs(memberCourseQueryWrapper).isEmpty()){
                return ServerResponseEntity.fail("U10004","该学员还有未完成的课程");
            }
            QueryWrapper<MemberCoursePlan> memberCoursePlanQueryWrapper = new QueryWrapper<>();
            memberCoursePlanQueryWrapper.eq("user_id", uid);
            if(!memberCoursePlanMapper.selectObjs(memberCoursePlanQueryWrapper).isEmpty()){
                return ServerResponseEntity.fail("U10004","该学员还有未完成的课程");
            }
            QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
            memberQueryWrapper.eq("user_id",uid);
            memberMapper.delete(memberQueryWrapper);
        }
        //如果是教练，则需要看该教练是否还有关联的课程，如果有，就不能删除该用户
        else if(roleName.equals("coach")){
            QueryWrapper<CoachCourse> coachCourseQueryWrapper = new QueryWrapper<>();
            coachCourseQueryWrapper.eq("user_id", uid);
            if(!coachCourseMapper.selectObjs(coachCourseQueryWrapper).isEmpty()){
                return ServerResponseEntity.fail("U10004","该教练还在执教");
            }
            QueryWrapper<Coach> coachQueryWrapper = new QueryWrapper<>();
            coachQueryWrapper.eq("user_id",uid);
            coachMapper.delete(coachQueryWrapper);
        }
        //删除该用户的角色
        QueryWrapper<RoleUser> roleUserQueryWrapper = new QueryWrapper<>();
        roleUserQueryWrapper.eq("user_id", uid);
        roleUserMapper.delete(roleUserQueryWrapper);

        //删除用户
        this.baseMapper.deleteById(uid);
        return ServerResponseEntity.success();
    }
}
